/**
 * Copyright &copy; 2020 <a href="https://github.com/somowhere/exam-system">exam-system</a> All rights reserved.
 */
package com.shanhesoft.java.modules.exam.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.shanhesoft.java.common.core.util.tree.TreeUtil;
import com.shanhesoft.java.common.core.vo.PageModel;
import com.shanhesoft.java.common.core.vo.TreeNode;
import com.shanhesoft.java.common.data.util.QueryWrapperUtil;
import com.shanhesoft.java.common.persistence.domain.TreeEntity;
import com.shanhesoft.java.common.persistence.service.impl.DataServiceImpl;
import com.shanhesoft.java.common.persistence.service.impl.TreeServiceImpl;
import com.shanhesoft.java.modules.exam.domain.TQuestionBank;
import com.shanhesoft.java.modules.exam.domain.dto.TQuestionBankDto;
import com.shanhesoft.java.modules.exam.domain.dto.TQuestionBankQueryCriteria;
import com.shanhesoft.java.modules.exam.domain.vo.TQuestionBankVo;
import com.shanhesoft.java.modules.exam.repository.TQuestionBankRepository;
import com.shanhesoft.java.modules.exam.service.TQuestionBankService;

import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 题库管理ServiceImpl 题库管理
 * @author admin
 * @version 2020-09-17 11:57:21
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class TQuestionBankServiceImpl extends TreeServiceImpl<TQuestionBankRepository, TQuestionBank, TQuestionBankDto> implements TQuestionBankService{
	@Override
	public void saveOrUpdate(TQuestionBankDto tQuestionBankDto) {
		// 想办法设置level值
		TQuestionBank tQuestionBank = this.getById(tQuestionBankDto.getParentId());
		if(null != tQuestionBank && null != tQuestionBank.getLevel()) {
			tQuestionBankDto.setLevel(tQuestionBank.getLevel() + 1);
		} else {
			tQuestionBankDto.setLevel(1L);
		}
		super.saveOrUpdate(tQuestionBankDto);
	}

	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public IPage<TQuestionBankVo> findTreeList(TQuestionBankQueryCriteria tQuestionBankQueryCriteria) {
		List<TQuestionBankVo> tQuestionBankVoList = repository.findVoList(QueryWrapperUtil.<TQuestionBank>getWrapper(tQuestionBankQueryCriteria)
			.eq(TreeEntity.F_SQL_DELFLAG, TreeEntity.FLAG_NORMAL).orderByAsc(TreeEntity.F_SQL_SORT));
		return new PageModel<>(Lists.newArrayList(TreeUtil.buildByLoopAutoRoot(tQuestionBankVoList)),
			tQuestionBankVoList.size());
	}

	@Override
	//@Cacheable(cacheNames = {"bank","tQuestionBankVo"}, key = "'findBankTreeNode:' + #p0")
	public List<TreeNode> findBankTreeNode(TQuestionBankQueryCriteria tQuestionBankQueryCriteria) {
		return super.getNodeTree(repository.selectList(QueryWrapperUtil.
			<TQuestionBank>getWrapper(tQuestionBankQueryCriteria).lambda().orderByAsc(TQuestionBank::getSort)));
	}
}
